package com.lhgray.sglhome.domain.usecase

import com.freightoa.foundation.net.ApiResult
import com.freightoa.foundation.net.bean.SGLResponse
import com.freightoa.foundation.presentation.domain.BaseUseCase
import com.lhgray.sglhome.domain.model.SourceData
import com.lhgray.sglhome.data.repository.BarCodeRepository
import javax.inject.Inject

class BarCodeUseCase @Inject constructor(private val barCodeRepository: BarCodeRepository) :
    BaseUseCase() {
    suspend operator fun invoke(barcode: String): Result<String> {
        return when (val fileNoByBarcode = barCodeRepository.getFileNoByBarcode(barcode)) {
            is ApiResult.Error -> Result.failure(RuntimeException(fileNoByBarcode.message))
            is ApiResult.Exception -> Result.failure(fileNoByBarcode.throwable)
            is ApiResult.Success -> processSuccessResult(fileNoByBarcode)

        }
    }
    private fun processSuccessResult(result:ApiResult.Success<SGLResponse<SourceData>>): Result<String> {
        // 获取数据
        val data = result.data.data ?: return Result.failure(NullPointerException("data is null"))
        // 检查数据是否为空
        // 获取列表项标签
        val listItemLabel = data.list_item_label
        // 检查列表项标签是否为空
        if (listItemLabel.isEmpty()) {
            return Result.failure(NullPointerException("data is null"))
        }
        // 获取第一个列表项的文本
        val itemText = listItemLabel.first().item_text
        // 检查文本是否为空
        return if (itemText.isNullOrEmpty()) {
            Result.failure(NullPointerException("data is null"))
        } else {
            Result.success(itemText)
        }
    }
}